<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applicantName">
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入申请人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="户主姓名" prop="accountName">
        <el-input
          v-model="queryParams.accountName"
          placeholder="请输入户主姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收款账户" prop="bankAccount">
        <el-input
          v-model="queryParams.bankAccount"
          placeholder="请输入收款账户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核时间">
        <el-date-picker
          v-model="daterangeApprovalTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['operations:audit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['operations:audit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['operations:audit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['operations:audit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="auditList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键ID" align="center" prop="id" /> -->
      <el-table-column label="订单号" align="center" prop="orderNo" />
      <el-table-column label="申请人" align="center" prop="applicantName" />
      <el-table-column label="打款金额" align="center" prop="amount" />
      <el-table-column label="户主姓名" align="center" prop="accountName" />
      <el-table-column label="收款账户" align="center" prop="bankAccount" />
      <el-table-column label="打款事由" align="center" prop="paymentReason" />
      <el-table-column label="审核状态" align="center">
        <template slot-scope="scope">
          <el-select v-model="scope.row.status" @change="handleStatusChange(scope.row)">
            <el-option label="未审核" :value="0"></el-option>
            <el-option label="通过" :value="1"></el-option>
            <el-option label="拒绝" :value="2"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="拒绝原因" align="center" prop="rejectReason" />
      <!-- <el-table-column label="拒绝人ID" align="center" prop="rejectBy" /> -->
      <el-table-column label="审核时间" align="center" prop="approvalTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['operations:audit:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改打款审批对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="关联订单" prop="orderId">
          <el-select v-model="form.orderId" placeholder="请选择关联订单" filterable>
            <el-option
              v-for="item in orderList"
              :key="item.id"
              :label="item.orderNo"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="打款金额" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入打款金额" />
        </el-form-item>
        <el-form-item label="户主姓名" prop="accountName">
          <el-input v-model="form.accountName" placeholder="请输入户主姓名" />
        </el-form-item>
        <el-form-item label="收款账户" prop="bankAccount">
          <el-input v-model="form.bankAccount" placeholder="请输入收款账户" />
        </el-form-item>
        <el-form-item label="打款事由" prop="paymentReason">
          <el-input v-model="form.paymentReason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAudit, getAudit, delAudit, addAudit, updateAudit, getOrderListForAudit } from "@/api/operations/audit"

export default {
  name: "Audit",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 打款审批表格数据
      auditList: [],
      // 订单列表
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeApprovalTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        applicantName: null,
        accountName: null,
        bankAccount: null,
        status: null,
        approvalTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        orderId: [
          { required: true, message: "关联订单ID不能为空", trigger: "blur" }
        ],
        applicantId: [
          { required: true, message: "申请人ID不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "打款金额不能为空", trigger: "blur" }
        ],
        accountName: [
          { required: true, message: "户主姓名不能为空", trigger: "blur" }
        ],
        bankAccount: [
          { required: true, message: "收款账户不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询打款审批列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeApprovalTime && '' != this.daterangeApprovalTime) {
        this.queryParams.params["beginApprovalTime"] = this.daterangeApprovalTime[0]
        this.queryParams.params["endApprovalTime"] = this.daterangeApprovalTime[1]
      }
      listAudit(this.queryParams).then(response => {
        this.auditList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderId: null,
        applicantId: null,
        amount: null,
        accountName: null,
        bankAccount: null,
        paymentReason: null,
        status: null,
        rejectReason: null,
        rejectBy: null,
        approvalTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeApprovalTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getOrderList()
      this.open = true
      this.title = "添加打款审批"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getOrderList()
      const id = row.id || this.ids
      getAudit(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改打款审批"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAudit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addAudit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除打款审批编号为"' + ids + '"的数据项？').then(function() {
        return delAudit(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('operations/audit/export', {
        ...this.queryParams
      }, `audit_${new Date().getTime()}.xlsx`)
    },
    /** 查询订单列表 */
    getOrderList() {
      getOrderListForAudit().then(response => {
        this.orderList = response;
      });
    },
    /** 审核状态修改 */
    handleStatusChange(row) {
      const newStatus = row.status;
      if (newStatus === 2) { // 拒绝
        this.$prompt('请输入拒绝原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({ value }) => {
          if (!value || value.trim() === '') {
            this.$message.error('拒绝原因不能为空');
            this.getList(); // revert
            return;
          }
          row.rejectReason = value;
          row.approvalTime = new Date();
          this.updateAuditStatus(row);
        }).catch(() => {
          this.$message.info('已取消操作');
          this.getList(); // revert
        });
      } else if (newStatus === 1) { // 通过
        this.$modal.confirm('是否确认将审核状态修改为"通过"？').then(() => {
          row.rejectReason = null;
          row.approvalTime = new Date();
          this.updateAuditStatus(row);
        }).catch(() => {
          this.getList(); // revert
        });
      } else if (newStatus === 0) { // 未审核
         this.$modal.confirm('是否确认将审核状态修改为"未审核"？').then(() => {
          row.rejectReason = null;
          row.approvalTime = null; // Clear approval time
          this.updateAuditStatus(row);
        }).catch(() => {
          this.getList(); // revert
        });
      }
    },
    updateAuditStatus(row) {
      updateAudit(row).then(response => {
        this.$modal.msgSuccess("修改成功");
      }).finally(() => {
        this.getList();
      });
    }
  }
}
</script>
